package com.xiaoyu.tool.handles;

import com.xiaoyu.tool.constant.WxClickEventKey;
import com.xiaoyu.tool.constant.WxRouterKey;
import com.xiaoyu.tool.entity.User.User;
import com.xiaoyu.tool.entity.kefu.KefuNews;
import com.xiaoyu.tool.enums.user.RelationshipType;
import com.xiaoyu.tool.handles.api.WxHandlerApi;
import com.xiaoyu.tool.repository.user.UserRepository;
import com.xiaoyu.tool.service.kefu.KefuNewsService;
import com.xiaoyu.tool.service.user.UserRelationShipAppletService;
import com.xiaoyu.tool.service.user.UserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author xiaoyu on 2018/7/6
 * 公众号消息监听后处理handler
 */
@Slf4j
@Component
public class WxHandler extends WxHandlerApi implements WxMpMessageHandler {

    @Value("${mp-kf.account}")
    private String account;

    @Value("${mp-kf.openId}")
    private String openId;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private KefuNewsService kefuNewsService;

    @Autowired
    private UserRelationShipAppletService userRelationShipAppletService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager){
        switch (wxMessage.getMsgType()){
            case WxRouterKey.EVENT:
                switch (wxMessage.getEvent()){
                    case WxRouterKey.SUBSCRIBE:
                        subscribeKefuMessage(wxMessage,wxMpService);//关注事件
                        break;
                    case WxRouterKey.UNSUBSCRIBE:
                        unSubscribeKefuMessage(wxMessage);//取消关注事件
                        break;
                    case WxClickEventKey.CLICK:
                        clickKefuMessage(wxMessage,wxMpService);//click菜单点击事件  两种情况
                        break;
                }
                break;
            case WxRouterKey.TEXT:
                textKefuMessage(wxMessage,wxMpService);
                break;
        }
        return null;
    }


    private void subscribeKefuMessage(WxMpXmlMessage wxMessage, WxMpService wxMpService){
        userService.updateOrCreateUser(wxMessage.getFromUser());
        User user = userRepository.findByOpenId(wxMessage.getFromUser());
        String eventKey = wxMessage.getEventKey();
        log.info("扫描带参数二维码事件:{}",eventKey);
        //扫描带参数二维码事件 - 用户未关注时，进行关注后的事件推送
        if (eventKey.startsWith("qrscene")) {
            String scene = eventKey.split("_")[1];
            userRelationShipAppletService.createRelationShipAndProfitApplet(user.getId(),Long.valueOf(scene), RelationshipType.二维码);
        }
        KefuNews kefuNews = kefuNewsService.findByEventAndEventKeyIsNull(wxMessage.getEvent());
        sendKefuMessage(wxMessage, wxMpService, kefuNews);
        return;
    }



    private void unSubscribeKefuMessage(WxMpXmlMessage wxMessage){
        userService.updateOrCreateUser(wxMessage.getFromUser());
    }

    private void clickKefuMessage(WxMpXmlMessage wxMessage, WxMpService wxMpService){
        KefuNews kefuNews = kefuNewsService.findByEventAndEventKey(wxMessage.getEvent(),wxMessage.getEventKey());
        sendKefuMessage(wxMessage, wxMpService, kefuNews);
    }

    private void sendKefuMessage(WxMpXmlMessage wxMessage, WxMpService wxMpService, KefuNews kefuNews) {
        try {
            clickKefuMessage(kefuNews,wxMessage,wxMpService);
        } catch (WxErrorException e) {
            log.error("客服消息发送失败:{}:{}:{}",kefuNews.getMsgType(),kefuNews.getEventKey(),kefuNews.getEvent());
        }
        log.info("执行:{}:{}:{}",kefuNews.getMsgType(),kefuNews.getEventKey(),kefuNews.getEvent());
    }



    private WxMpXmlOutMessage kefuMessage(WxMpXmlMessage wxMessage, WxMpService wxMpService){
        if (wxMessage.getContent().equals(WxClickEventKey.LABOUR)) {
            KefuNews kefuNews = kefuNewsService.findByEventAndEventKey(wxMessage.getMsgType(),wxMessage.getContent());
            try {
                clickKefuMessage(kefuNews,wxMessage,wxMpService);
            } catch (WxErrorException e) {
                log.error("客服消息发送失败:{}:{}:{}", kefuNews.getMsgType(),kefuNews.getEventKey(),kefuNews.getEvent());
            }
            log.info("执行客服连接:{}:{}:{}",kefuNews.getMsgType(),kefuNews.getEventKey(),kefuNews.getEvent());
            try {
                //创建人工客服连接
                wxMpService.getKefuService().kfSessionCreate(wxMessage.getFromUser(),account);
            } catch (WxErrorException e) {
                log.error("创建客服消息失败:{}",e.getMessage());
            }
            try {
                sendTextMessage(openId,wxMpService,"有用户联系客服,\r请登录微信客服系统进行处理");
            } catch (WxErrorException e) {
                log.error("执行客服通知:{}",e.getMessage());
            }
        }else if (wxMessage.getContent().equals(WxClickEventKey.END)) {
            try {
                WxHandlerApi.sendTextMessage(wxMessage.getFromUser(),wxMpService,"此次咨询结束,感谢您的信任!");
            } catch (WxErrorException e) {
                log.info("人工客服消息结束发送失败:{}",e.getMessage());
            }
        }
        return null;
    }

    private void textKefuMessage(WxMpXmlMessage wxMessage, WxMpService wxMpService){
        KefuNews kefuNews = kefuNewsService.findByEventAndEventKey(wxMessage.getMsgType(),wxMessage.getContent());
        if (kefuNews == null){
            return;
        }
        try {
            clickNewsKefuMessage(kefuNews,wxMessage,wxMpService);
        } catch (WxErrorException e) {
            log.error("客服消息发送失败:{}:{}:{}",kefuNews.getMsgType(),kefuNews.getEventKey(),kefuNews.getEvent());
        }
        log.info("执行:{}:{}:{}",kefuNews.getMsgType(),kefuNews.getEventKey(),kefuNews.getEvent());
    }

}

